package cn.zengdeai.langchain4j_springboot.controller;

import cn.zengdeai.langchain4j_springboot.config.DaobaoAiConfig;
import cn.zengdeai.langchain4j_springboot.pojo.ChatRequest;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.service.TokenStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.LocalDate;

@RestController
@RequestMapping("/dbai")
public class DoubaoController {


    @Autowired
    OpenAiChatModel openAiChatModel;

    @Autowired
    OpenAiStreamingChatModel openAiStreamingChatModel;

    @Autowired
    ChatModel chatModel;

    @Autowired
    DaobaoAiConfig.DaobaoAssistant doubaoAssistant;

    @RequestMapping("/opaiChat")
    public String openAiChat(@RequestParam(defaultValue = "你是谁") String message){
        return openAiChatModel.chat(message);
    }

    @RequestMapping("/generalChat")
    public String generalChat(@RequestParam(defaultValue = "你是谁") String message){
        return chatModel.chat(message);
    }

    @RequestMapping(value = "/openai_memory_chat")
    public String openAiMemoryChat(@RequestParam(defaultValue = "我叫万德军") String message) {
        return doubaoAssistant.chat(message);
    }


    /**
     * 流式对话
     * @param message
     * @return
     */
    @RequestMapping(value = "/stream", produces = "text/stream;charset=UTF-8")
    public Flux<String> streamChat(@RequestParam(defaultValue = "你是谁") String message) {

        Flux<String> objectFlux = Flux.create(fluxSink -> {
            openAiStreamingChatModel.chat(message, new StreamingChatResponseHandler() {
                @Override
                public void onPartialResponse(String s) {
                    fluxSink.next(s);
                }

                @Override
                public void onCompleteResponse(ChatResponse chatResponse) {
                     fluxSink.complete();
                }

                @Override
                public void onError(Throwable throwable) {
                    fluxSink.error(throwable);
                }
            });
        });
        return objectFlux;
    }


    /**
     * 多轮对话记忆+流式+知识库
     * @param message
     * @param response
     * @return
     */
    @RequestMapping(value = "/memory_stream_chat", produces = "text/stream;charset=UTF-8")
    public Flux<String> memoryStreamChat(@RequestParam(defaultValue = "我是谁") String message, HttpServletResponse response) {
        TokenStream stream = doubaoAssistant.stream(message);

        return Flux.create(sink -> {
            stream.onPartialResponse(s -> sink.next(s))
                    .onCompleteResponse(c -> sink.complete())
                    .onError(sink::error)
                    .start();

        });
    }


//    @RequestMapping(value = "/memory_stream_csr_chat", produces = "text/stream;charset=UTF-8")
    @PostMapping("/memory_stream_csr_chat")
    public Flux<String> memoryStreamCsrChat(@RequestBody ChatRequest request, HttpServletResponse response) {
//        TokenStream stream = doubaoAssistant.stream(buildPrompt(request.getMessage()));
        TokenStream stream = doubaoAssistant.stream(request.getMessage());

        return Flux.create(sink -> {
            stream.onPartialResponse(s -> sink.next(s))
                    .onCompleteResponse(c -> sink.complete())
                    .onError(sink::error)
                    .start();

        });
    }


    /**
     * 通过商品标题生成AI人设
     * @param request
     * @param response
     * @return
     */
//    @GetMapping(value = "/chatTl", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @PostMapping(value = "/memory_stream_build_product_title",produces =  MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> memoryStreamBuildProductTitle(@RequestBody ChatRequest request, HttpServletResponse response) {
        TokenStream stream = doubaoAssistant.streamToBuildTitle(request.getMessage());

        return Flux.create(sink -> {
            stream.onPartialResponse(s ->
            {
                System.out.println("s:" + s);
                sink.next(s);

            })
                    .onCompleteResponse(c -> sink.complete())
                    .onError(sink::error)
                    .start();

        });
    }


    private String buildPrompt(String message){
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("标题是:")
                .append(message)
                .append(" AI脚本:");
        return stringBuilder.toString();

    }


}
